<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogFormVisible"
    @close="closeDlg()"
    destroy-on-close
    width="600px"
  >
    <div>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="wapperSon">
            <el-autocomplete
              class="inline-input"
              style="max-width:120px;font-size:12px;"
              v-model="queryConditions.produceLineNo"
              :fetch-suggestions="querySearch"
              placeholder="生产工序线"
              @select="handleSelect"
              @input="handleInput"
            ></el-autocomplete>
          </div> </el-col
        ><el-col :span="12">
          <div class="wapperSon">
            <el-button-group style="float: left">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="getUnSceduledLines"
                >查询</el-button
              >
              <el-button
                type="primary"
                 icon="el-icon-plus"
                @click="addProduceLines"
              >
                添加
              </el-button>
            </el-button-group>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>生产工序线列表</span>
          </div>
          <el-row type="flex" justify="start">
            <el-table
              v-loading="listLoading"
              :data="lstProduceLines"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="生产线编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.produceLineNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="生产线"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.produceLineName }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-card>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  getAll,
  getList,
  create,
  update,
  deleteBatch,
  getOrderProductDtlVo
} from "@/api/sale/saleOrderProductNoDtl";

import {
  getAll as queryAllOrders,
  create as createProducePlan,
  getUnSceduledProduceLines,
  getUnReverseSceduledProduceLines,
  sceduledProduceLine
} from "@/api/produce/schedulePlan/ProduceOrderProductPlanApi";
import moment, { duration } from "moment";

export default {
  name: "producelineselectdlg",
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  props: {
    dialogVisible: false,
    scheduleMethod: 0
  },
  watch: {
    dialogVisible: function(newValue, oldValue) {
      if (newValue != null) {
        this.dialogFormVisible = newValue;
        if (newValue) {
        }
      }
    },
    scheduleMethod: function(newValue, oldValue) {
      if (newValue != null) {
        this.temp.planMethod = newValue;
        if (this.dialogFormVisible && newValue) {
          if (this.temp.planMethod == 1) {
            this.getUnSceduledLines();
          } else {
            this.getUnReverseSceduledProduceLines();
          }
        }
      }
    },
    planSort: function(newValue, oldValue) {
      if (newValue != null && newValue != oldValue) {
        this.temp.planSort = newValue;
      }
    },
    deep: true
  },
  data() {
    return {
      data2: [],
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentSaleOrderMstTypeId: 0,
      dialogFormVisible: false,
      dialogTitle: "选择产线",
      //表格變量
      lstSelected: [],
      queryConditions: {
        produceLineNo: ""
      },
      lstOrders: [],
      deliveryDates: [],
      lstProduceLines: [],
      temp: {
        productNo: "",
        deliveryDate: "",
        scheduleSate: 0,
        produceLineId: 0,
        qty: 0, //计划数量
        transferQty: 1, //转移量
        bottleNeckCacheRatio: 1, //瓶颈提前期比例
        materialCacheQty: 1, //投料提前期
        calculateStartDate: "", //开始计算时间，为空默认为当天
        planMethod: 0, //排产方式 1:正排，2:倒排
        planSort: 1 //1:按交期顺序排产;2:按优先级顺序排产
      }
    };
  },
  computed: {},
  created() {
    if (this.temp.planMethod == 1) {
      this.getUnSceduledLines();
    } else if (this.temp.planMethod == 2) {
      this.getUnReverseSceduledProduceLines();
    }
  },

  methods: {
    resetTemp() {
      this.temp = {
        productNo: "",
        deliveryDate: "",
        scheduleSate: 0,
        produceLineId: 0,
        qty: 0, //计划数量
        transferQty: 1, //转移量
        bottleNeckCacheRatio: 1, //瓶颈提前期比例
        materialCacheQty: 1, //投料提前期
        calculateStartDate: "", //开始计算时间，为空默认为当天
        planMethod: 0, //排产方式 :正排，1:倒排
        planSort: 1 //1:按交期顺序排产;2:按优先级顺序排产
      };
    },
    handleSelectionChange(val) {
      this.lstSelected = val;
      const type = this.list.find(v => v.therbligsNo === val.therbligsNo);
      if (type != null) {
        this.currentSaleOrderMstTypeId = type.id;
      }
    },
    querySearch(queryString, cb) {
      let results = this.lstOrders;
      results = queryString
        ? this.lstOrders.filter(this.createFilter(queryString))
        : this.lstOrders;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return p => {
        return p.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    handleSelect(val) {
      this.queryConditions.produceLineNo = val.value;
    },
    handleInput(val) {
      this.queryConditions.produceLineNo = val;
    },
    //获取所有的正序未排产的产线
    getUnSceduledLines() {
      this.listLoading = true;
      let params = { produceLineNo: "" };
      params = Object.assign(params, this.queryConditions);
      getUnSceduledProduceLines(params).then(response => {
        this.lstProduceLines.length = 0;
        let result = response.data;
        if (result != null && result.length > 0) {
          this.lstProduceLines = result;
          this.lstOrders.length = 0;
          result.map(v => {
            this.lstOrders.push({ value: v.produceLineNo });
          });
        }
        this.listLoading = false;
      });
    },
    //获取所有的倒序未排产的产线
    getUnReverseSceduledProduceLines() {
      this.listLoading = true;
      let params = { produceLineNo: "" };
      params = Object.assign(params, this.queryConditions);
      getUnReverseSceduledProduceLines(params).then(response => {
        this.lstProduceLines.length = 0;
        let result = response.data;
        if (result != null && result.length > 0) {
          this.lstProduceLines = result;
          this.lstOrders.length = 0;
          result.map(v => {
            this.lstOrders.push({ value: v.produceLineNo });
          });
        }
        this.listLoading = false;
      });
    },
    closeDlg() {
      this.dialogFormVisible = false;
      //this.planMethod = 0;
      this.$emit("hideDlg", this.dialogFormVisible);
    },
    addProduceLines() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条产线!");
        return;
      }
      let hasErr = false;

      //构造一条排产计划
      let params = Object.assign({},this.temp);
      params.produceLineId = this.lstSelected[0].produceLineId;
      params.produceLineNo = this.lstSelected[0].produceLineNo;
      params.produceLineName = this.lstSelected[0].produceLineName;
      //params.planMethod = this.temp.planMethod
      //debugger;
      //保存
      sceduledProduceLine(params)
        .then(() => {
          this.$emit("refreshTbl");
        })
        .catch(err => {
          hasErr = true;
          console.log(err);
        });
      if (!hasErr) {
        this.$notify({
          title: "Success",
          message: "添加成功！",
          type: "success",
          duration: 2000
        });
        this.dialogFormVisible = false;
      }
    }
  }
};
</script>
<style scoped>
.item1 {
  margin-top: 20px;
}
.wapperSon {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.app-container {
  padding: 0;
}
</style>
